package com.jwell.cargoapp.ui.base

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.jwell.cargoapp.ui.dialog.LoadingDialog
import com.jwell.cargoapp.ui.dialog.NoTitleDialog
import com.jwell.panrank.application.App
import com.jwell.panrank.ui.activity.LoginActivity
import com.jwell.panrank.ui.activity.MainActivity

/**
 * 基础 Fragment
 */
open class BaseFragment : Fragment(), IBaseView {

    var dialog: Dialog? = null
    var loading: Dialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    private fun returnActivity() {
        /**隐藏软键盘**/
        val view = activity?.window?.peekDecorView()
        if (view != null) {
            val inputmanger = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputmanger.hideSoftInputFromWindow(view.windowToken, 0)
        }
        activity?.finish()
    }

    override fun showProgress(message: String, outIsTouch: Boolean) {
        try {
            loading = LoadingDialog.Builder(context)
                    .setOutouch(outIsTouch)
                    .setDescrible(message)
                    .creat() as Dialog
            loading?.show()
        } catch (e: Exception) {
            e.printStackTrace()
            loading?.dismiss()
            loading = null
        }

    }

    override fun hideProgress() {
        loading?.dismiss()
    }

    override fun showDialog(message: String, ensureListener: DialogInterface.OnClickListener?, cancelListener: DialogInterface.OnClickListener?) {
        try {
            dialog = NoTitleDialog.Builder(context!!)
                    .setMessage(message)
                    .setOnCancelClickListener(cancelListener)
                    .setOnEnsureClickListener(ensureListener)
                    .create()
            dialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
            dialog?.dismiss()
            dialog = null
        }

    }

    override fun hideDialog() {
        dialog?.hide()
    }

    override fun skipToMain(bundle: Bundle?) {
        var intent = Intent(context, MainActivity::class.java)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
        activity?.finish()
    }

    override fun skipToLogin(finsh: Boolean) {
        var intent = Intent(context, LoginActivity::class.java)
        startActivity(intent)
        if (finsh) {
            activity?.finish()
        }
    }

    override fun toast(message: String) {
        Toast.makeText(App.instance, message, Toast.LENGTH_SHORT).show()
    }

}